<?php

class TransactionController extends Zend_Controller_Action
{
	private $_auth;
	private $_acl;
    private $_params;
    private $_memcache;
    private $_my_mem;
    public function init(){
        $acl                = new My_Acl();
        $this->_acl         = $acl;
        $auth               = $acl->checkAllowed($this->_request);
        $this->_auth        = $auth->getIdentity();
        $this->view->auth   = $this->_auth;
        $this->_acl         = $acl;
        $this->view->acl    = $this->_acl;
        $this->_params      = $this->_request->getParams();
        
        $memcache = new Memcache;
        $memcache->connect('localhost', MEMCACHE_PORT) or die ("Could not connect");
        $this->_memcache = $memcache;
        $_my_mem = new My_Mem();
        $this->_my_mem = $_my_mem;
    }
    public function indexAction(){
    return;
        # get time start and time end of statistic
        $_params            = $this->_params;
        $myKpi              = new My_Service_Kpi();
        
        $gameId             = $_params['game'];
        $this->view->gameId = $gameId;
        $modelGame          = new Default_Model_Game();
        $gameCheck          = $modelGame->getDataById($gameId)->toArray();
        if($gameCheck){
            $this->view->gameCheck = $gameCheck;
            if(file_exists(CONFIG_PATH . '/'.$gameId.'.ini')){
                #config ssgroup and config game
                $configGame = new Zend_Config_Ini(CONFIG_PATH . '/'.$gameId.'.ini', APPLICATION_ENV);
                $modelRole          = new Default_Model_Role();
                $roleList           = $modelRole->getDataByUserIdGameId($this->_auth['userId'],$gameId)->toArray();
                $channelDisabled    = array();
                foreach($roleList as $row){
                    if(isset($row['channelDisabled']) && $row['channelDisabled']){
                        if(is_array(json_decode($row['channelDisabled']))){
                            $channelDisabled    = array_merge($channelDisabled,json_decode($row['channelDisabled']));
                        }
                    }
                }
                if(isset($configGame->channel)){
                    $channelGame = array();
                    foreach($configGame->channel->toArray() as $key=>$value){
                        $channelGame[] = $key;
                    }
                }
                #prTien($channelGame);
                $channelIntersect = array_intersect($channelDisabled,$channelGame);
                $arrTemp = array();
                if(count($channelIntersect) && isset($configGame->pcu->viewChannel) && $configGame->pcu->viewChannel == 1){
                    $this->view->disabledViewTotal = 1;
                    foreach($channelGame as $row){
                        if(!in_array($row,$channelIntersect)){
                            if(isset($configGame->channel->$row->value)){
                                $arrTemp = array_merge($arrTemp,$configGame->channel->$row->value->toArray());
                            }
                        }
                    }
                    $arrTemp = array_unique($arrTemp);
                }
                // check repair chuc nang
                if($this->_acl->checkRepair($this->_request, $gameCheck['repair'])){
                    $this->view->repair = 'repair';
                    if(isset($configGame->repair->type) && isset($configGame->repair->content)){
                        $this->view->flag = $configGame->repair->type;
                        $this->view->mess = $configGame->repair->content;
                    }else{
                        $this->view->flag = 'alert';
                        $this->view->mess = 'Chức năng đang được bảo trì. Xin lỗi vì sự bất tiện này';
                    }
                    return;
                }
                $this->view->configGame = $configGame;
                
                $channels       = $configGame->channel->toArray();
                foreach($channels as $key=>$row){
                    if(!isset($channelDisabled[0]) || (isset($channelDisabled[0]) && !in_array($key,$channelDisabled))){
                        
                    }else{
                        unset($channels[$key]);
                    }
                }
                $this->view->arrChannel = $channels;
                
                if(isset($configGame->server)){
                    $arrServer = $configGame->server->toArray();
                    $temp = array();
                    foreach($arrServer as $key=>$server){
                        if($arrTemp){
                            if(isset($server['name']) && in_array($key,$arrTemp)){
                                $temp[$key] = $server['name'];
                            }
                        }else{
                            if(isset($server['name'])){
                                $temp[$key] = $server['name'];
                            }
                        }
                    }
                    $arrServer = $temp;
                    $this->view->arrServer = $arrServer;
                }
                                    
                if(isset($_params['bntSubmit']) && $_params['bntSubmit'] == 'Tìm'){
                    $username = '';
                    $dateStart = '';
                    $dateEnd = '';
                    $channel = '';
                    $serverId = '';
                    $status = '';
                    if(!isset($_params['username']) || !$_params['username']){
                        $this->view->mess = 'Vui lòng nhập username!';
                        $this->view->flag = 'alert';
                        return;
                    }
                    if(!isset($_params['dateStart']) || !$_params['dateStart']){
                        $this->view->mess = 'Vui lòng nhập ngày bắt đầu!';
                        $this->view->flag = 'alert';
                        return;
                    }
                    if(!isset($_params['dateEnd']) || !$_params['dateEnd']){
                        $this->view->mess = 'Vui lòng nhập ngày kết thúc!';
                        $this->view->flag = 'alert';
                        return;
                    }
//                    if(isset($configGame->transaction->server) || $configGame->transaction->server != 1){
//                        if(!isset($_params['serverId']) && !$_params['serverId']){
//                            $this->view->mess = 'Vui lòng chọn server!';
//                            $this->view->flag = 'alert';
//                            return;
//                        }
//                    }
                    
                    $username               = trim($_params['username']);
                    $this->view->username   = $username;
                    
                    $dateStart              = $_params['dateStart'];
                    if($dateStart >= date("Y-m-d"))
                        $dateStart = date("Y-m-d");
                    $this->view->dateStart  = $dateStart;
                    
                    $dateEnd                = $_params['dateEnd'];
                    if($dateEnd >= date("Y-m-d"))
                        $dateEnd = date("Y-m-d");
                    $this->view->dateEnd    = $dateEnd;
                                        
                    if(isset($_params['channel'])){
                        $channel                = $_params['channel'];
                        if(in_array($channel,$channelDisabled)){
                            $this->view->mess = 'Không có dữ liệu!';
                            $this->view->flag = 'alert';
                            return;
                        }
                        $this->view->channel    = $channel;
                    }
                    
                    if(isset($_params['serverId'])){
                        $serverId               = $_params['serverId'];
                        if($arrTemp && !in_array($serverId,$arrTemp)){
                            $this->view->mess = 'Không có dữ liệu!';
                            $this->view->flag = 'alert';
                            return;
                        }
                        $this->view->serverId   = $serverId;
                    }
                    
                    if(isset($_params['status']) && $_params['status'] != -1){
                        $status                 = $_params['status'];
                        $this->view->status     = $status;
                    }
                
                    #init service
                    $conn       = new My_Service_Soap();
                    $service    = $conn->getClient($configGame->transaction);
                    
                    $configTransaction      = $configGame->transaction->toArray();
                    $configTransaction['startDate']         = $dateStart;
                    $configTransaction['dateEnd']           = $dateEnd;
                    $configTransaction['username']          = $username;
                    $configTransaction['serverId']          = $serverId;
                    $configTransaction['status']            = $status;
                    $configTransaction['channelingAgentId'] = $channel;
                    
                    $urlModule      = $this->_request->getModuleName();
                    $urlController  = $this->_request->getControllerName();
                    $urlAction      = $this->_request->getActionName();
                    $keyMem = 'mc_'.BASE_URL.'_'.ENV.'_'.$gameId.'_'.$urlController.'_'.$urlAction.'_'.$dateStart.'_'.$dateEnd.'_'.md5($urlModule.$urlController.$urlAction.$gameId.$dateStart.$dateEnd.$username.$serverId.$status.$channel);
                    #$this->_memcache->delete($keyMem);
                    $data = array();
                    if($this->_memcache->get($keyMem) && in_array($urlModule.'/'.$urlController,$configGame->cache->controller->toArray())){
                        $data = $this->_my_mem->get($keyMem, $configGame->cache->time, $this->_memcache);
                    }else{
                        try{
                            $params     = $conn->{$configTransaction['prepareParams3']}($configTransaction);
                            $data       = $service->{$configTransaction['function']}($params);
                            #echo '<pre>',print_r($params),'</pre>';
                            #echo '<pre>',print_r($data),'</pre>';
                            if(isset($data['status']) && $data['status'] == 1){
                                if($dateEnd < date("Y-m-d")){
                                    $this->_my_mem->set($keyMem,serialize($data),false,$configGame->cache->time, $this->_memcache);
                                }
                            }elseif(isset($data['status']) && ($data['status'] == "-3001" || $data['status'] == "-1004")){
                                $this->view->mess = 'Không có dữ liệu!';
                                $this->view->flag = 'alert';
                                return;
                            }
                        }catch(Exception $ex){
                            $myKpi->writeLog(array('wsdl'=>$configGame->applications->wsdl,'params'=>$params,'mess'=>$ex->getMessage()),$gameId);
                            if(isset($configGame->mess->serviceError)){
                                $mess = $configGame->mess->serviceError;
                            }else{
                                $mess = 'Có lỗi khi truy vấn dữ liệu. Vui lòng thử lại khi khác!';
                            }
                            $this->view->mess = $mess;
                            $this->view->flag = 'error';
                            return;
                        }
                    }
                    # Sap xep giam dan
                    if(isset($data['status']) && $data['status'] == 1 && isset($data['result']) && is_array($data['result'])){
                        $count = count($data['result']);
                        for($i = 0; $i < $count; ++$i){
                            for($j = $i+1; $j < $count; ++$j){
                                if($data['result'][$i]['update_date'] < $data['result'][$j]['update_date']){
                                    $temp = $data['result'][$i];
                                    $data['result'][$i] = $data['result'][$j];
                                    $data['result'][$j] = $temp;
                                }
                            }
                        }
                    }
                    #echo '<pre>',print_r($data),'</pre>';
                    if(isset($data['status']) && $data['status'] == 1){
                        $data = $data['result'];
                        $knb = 0;
                        $gold = 0;
                        foreach($data as $row){
                            if(isset($row['status'])){
                                if(isset($row['statusAll'])){
                                    if($row['statusAll'] == 1){
                                        $checkStatus = "Thành công";
                                    }else{
                                        if(isset($configGame->transaction->success)){
                                            $success = ','.$configGame->transaction->success.',';
                                        }else{
                                            $success = ',1,';
                                        }
                                        $checkStatus = strrpos('checkStatus_'.$row['statusAll'],$success);
                                        if($checkStatus > 1){
                                            $checkStatus = "Thành công";
                                        }else{
                                            $checkStatus = "Thất bại";
                                        }
                                    }
                                }else{
                                    if($row['status'] == 1){
                                        $checkStatus = "Thành công";
                                    }
                                }
                            }
                            if($checkStatus == "Thành công"){
                                if(isset($row['knb'])){
                                    $knb += $row['knb'];
                                }
                                if(isset($row['gold'])){
                                    $gold += $row['gold'];
                                }
                                #echo $knb." : ".$gold."<br />";                                
                            }
                        }
                        $this->view->totalRecord    = count($data);
                        $this->view->totalKnb       = $knb;
                        $this->view->totalGold      = $gold;
                    }else{
                        $this->view->mess = 'Chưa có dữ liệu!';
                        $this->view->flag = 'alert';
                        return;
                    }
                            
                    $paginator = Zend_Paginator::factory($data);
                    $paginator->setItemCountPerPage(30);        
                    $paginator->setPageRange(10);
                    $currentPage = $this->_request->getParam('page',1);
                    $paginator->setCurrentPageNumber($currentPage);
                    $this->view->data=$paginator;
                    
                    $urlModule      = $this->_request->getModuleName();
                    $urlController  = $this->_request->getControllerName();
                    $urlAction      = $this->_request->getActionName();
                    
                    $this->view->keyMem      = 'transaction'.md5($keyMem);	
                    $ss = new Zend_Session_Namespace('transaction'.md5($keyMem));		
                    if($dateStart == $dateEnd){
                        $ss->exportName  = 'Transaction_'.$gameId.'_'.$dateStart;
                    }else{
                        $ss->exportName  = 'Transaction_'.$gameId.'_'.$dateStart.'_'.$dateEnd;
                    }		
        			$ss->exportData  = $data;			
        		}
            }else{
                $this->view->mess = 'Chưa có setting cho game!';
                $this->view->flag = 'error';
                    $this->view->repair = 1;
            }
        }
    }
    public function exportAction(){
        
        $urlModule      = $this->_request->getModuleName();
        $urlController  = $this->_request->getControllerName();
        $urlAction      = $this->_request->getActionName();
        $_params = $this->_params;
        $keyMem = $_params['keyMem'];
        
        $gameId             = $_params['game'];
        $modelGame          = new Default_Model_Game();
        $gameCheck          = $modelGame->getDataById($gameId)->toArray();
        if(!$gameCheck){
            $this->_helper->redirector('transaction','index');
        }
        if(file_exists(CONFIG_PATH . '/'.$gameId.'.ini')){
            #config ssgroup and config game
            $configGame = new Zend_Config_Ini(CONFIG_PATH . '/'.$gameId.'.ini', APPLICATION_ENV);
        }else{
            $this->_helper->redirector('transaction','index');
        }
		$ss = new Zend_Session_Namespace($keyMem);						
		$exportName   = $ss->exportName;					
		$exportData   = $ss->exportData;
        //prTien($exportData);
        $count = count($exportData);
        for($i = 0; $i < $count; ++$i){
            for($j = $i+1; $j < $count; ++$j){
                if($exportData[$i]['update_date'] > $exportData[$j]['update_date']){
                    $temp = $exportData[$i];
                    $exportData[$i] = $exportData[$j];
                    $exportData[$j] = $temp;
                }
            }
        }
        //prTien($exportData);
        if(count($exportData) == 0){
            $this->_helper->redirector('index','index');
            exit;
        }
        
	    Zend_Layout::getMvcInstance()->disableLayout();
	    $this->_helper->viewRenderer->setNoRender();
   	    $helper_time = $this->_helper->time;
        error_reporting(E_ERROR | E_WARNING | E_PARSE);
			
        $workbook = My_Pear::getInstanceSpreadsheet();
	    $workbook->setVersion(8, 'utf-8'); 
		$worksheet1 = &$workbook->addWorksheet("Transaction detail game ".$gameId); 
        $worksheet1->setInputEncoding('utf-8');
        
        if(isset($configGame->transaction->tranPartner) && $configGame->transaction->tranPartner == 1){
            $worksheet1->setColumn(0,0,5);
            $worksheet1->setColumn(1,3,35);
            if(isset($configGame->transaction->gold) && $configGame->transaction->gold == 1){
                $worksheet1->setColumn(4,5,10);
                $worksheet1->setColumn(6,6,20);
                $worksheet1->setColumn(7,8,15);
                $worksheet1->setColumn(8,15,15);
                $totalColumn = array('4'=>'E','5'=>'F');
            }else{
                $worksheet1->setColumn(4,4,10);
                $worksheet1->setColumn(5,5,20);
                $worksheet1->setColumn(6,7,15);
                $worksheet1->setColumn(7,15,15);
                $totalColumn = array('4'=>'E');
            }
        }else{
            $worksheet1->setColumn(1,2,35);
            if(isset($configGame->transaction->gold) && $configGame->transaction->gold == 1){
                $worksheet1->setColumn(3,4,10);
                $worksheet1->setColumn(5,5,20);
                $worksheet1->setColumn(6,7,15);
                $worksheet1->setColumn(7,15,15);
                $totalColumn = array('3'=>'D','4'=>'E');
            }else{
                $worksheet1->setColumn(3,3,10);
                $worksheet1->setColumn(4,4,20);
                $worksheet1->setColumn(5,6,15);
                $worksheet1->setColumn(6,15,15);
                $totalColumn = array('3'=>'D');
            }
        }
        
		//end style	
		$header = &$workbook->addFormat(); 
		$header->setBold(); 
		$header->setColor('white'); 
        $header->setFgColor('23'); 
		$header->setAlign('vcentre');
		$header->setHAlign('center'); 
		$header->setVAlign('center'); 
		$header->setBorder(1); 	
        $header->setTextWrap();

		$sttStyle = &$workbook->addFormat(); 
		$sttStyle->setAlign('vcentre');
		$sttStyle->setHAlign('center'); 
		$sttStyle->setVAlign('center'); 
        $sttStyle->setBorder(1);
        $sttStyle->setTextWrap();

		$textStyle = &$workbook->addFormat(); 
		$textStyle->setAlign('vcentre');
		$textStyle->setHAlign('left'); 
		$textStyle->setVAlign('center'); 
        $textStyle->setBorder(1);
        $textStyle->setTextWrap();

		$textStyleTotal = &$workbook->addFormat(); 
		$textStyleTotal->setColor('red'); 
		$textStyleTotal->setAlign('vcentre');
		$textStyleTotal->setHAlign('right'); 
		$textStyleTotal->setVAlign('center'); 
        $textStyleTotal->setBorder(1);
        $textStyleTotal->setTextWrap();

		$textStyleFalse = &$workbook->addFormat(); 
		$textStyleFalse->setColor('red'); 
		$textStyleFalse->setAlign('vcentre');
		$textStyleFalse->setHAlign('left'); 
		$textStyleFalse->setVAlign('center'); 
        $textStyleFalse->setBorder(1);
        $textStyleFalse->setTextWrap();
		
		$numberFormat = &$workbook->addFormat();
		$numberFormat->setHAlign('right'); 
		$numberFormat->setVAlign('center'); 
		$numberFormat->setNumFormat('#,###');
        $numberFormat->setBorder(1);
        $numberFormat->setTextWrap();
		
		$numberFormatTotal = &$workbook->addFormat();
		$numberFormatTotal->setColor('red'); 
		$numberFormatTotal->setHAlign('right'); 
		$numberFormatTotal->setVAlign('center'); 
		$numberFormatTotal->setNumFormat('#,###');
        $numberFormatTotal->setBorder(1);
        $numberFormatTotal->setTextWrap();
        //title
        $num_column = 0;
        $num_row = 0;       
        $worksheet1->write(0, $num_column, 'STT', $header);
        
        $name_trans_ID = 'Transaction ID';
        if(isset($configGame->transaction->allow->excel->trans_ID)){
            $name_trans_ID = $configGame->transaction->allow->excel->trans_ID;
        }
        $name_trans_Partner_ID = 'Partner Transaction ID';
        if(isset($configGame->transaction->allow->excel->trans_Partner_ID)){
            $name_trans_Partner_ID = $configGame->transaction->allow->excel->trans_Partner_ID;
        }
        $name_username = 'Username';
        if(isset($configGame->transaction->allow->excel->username)){
            $name_username = $configGame->transaction->allow->excel->username;
        }
        $name_gold = 'Tiền trong game';
        if(isset($configGame->transaction->allow->excel->gold)){
            $name_gold = $configGame->transaction->allow->excel->gold;
        }
        $name_gold_convert = 'Tiền convert';
        if(isset($configGame->transaction->allow->excel->gold_convert)){
            $name_gold_convert = $configGame->transaction->allow->excel->gold_convert;
        }
        $name_date = 'Ngày';
        if(isset($configGame->transaction->allow->excel->date)){
            $name_date = $configGame->transaction->allow->excel->date;
        }
        $name_server = 'Server';
        if(isset($configGame->transaction->allow->excel->server)){
            $name_server = $configGame->transaction->allow->excel->server;
        }
        $name_channel = 'Channel';
        if(isset($configGame->transaction->allow->excel->channel)){
            $name_channel = $configGame->transaction->allow->excel->channel;
        }
        $name_status = 'Trạng thái';
        if(isset($configGame->transaction->allow->excel->status)){
            $name_status = $configGame->transaction->allow->excel->status;
        }
        
        $worksheet1->write(0, ++$num_column, $name_trans_ID, $header);
        if(isset($configGame->transaction->tranPartner) && $configGame->transaction->tranPartner == 1){
            $worksheet1->write(0, ++$num_column, $name_trans_Partner_ID, $header);
        }
        $worksheet1->write(0, ++$num_column, $name_username, $header);
        $worksheet1->write(0, ++$num_column, $name_gold, $header);
        if(isset($configGame->transaction->gold) && $configGame->transaction->gold == 1){
            $worksheet1->write(0, ++$num_column, $name_gold_convert, $header);
        }
        $worksheet1->write(0, ++$num_column, $name_date, $header);
		if(!isset($configGame->transaction->server) || (isset($configGame->transaction->server) && $configGame->transaction->server == 1)){
			$worksheet1->write(0, ++$num_column, $name_server, $header);
		}
        if(!isset($configGame->transaction->agent_id) || (isset($configGame->transaction->agent_id) && $configGame->transaction->agent_id == 1)){
            $worksheet1->write(0, ++$num_column, $name_channel, $header);
        }
        $worksheet1->write(0, ++$num_column, $name_status, $header);
        
        //end title
        $stt = 1;
        $num_row = 1;
        foreach($exportData as $key=>$data){
            $num_column = 0;
            $server = $data['server_id'];
            if(isset($configGame->server->$data['server_id']->name))
                $server = $configGame->server->$data['server_id']->name;
            if(isset($data['statusAll'])){
                if($data['statusAll'] == 1){
                    $status = "Thành công";
                }else{
                    if(isset($configGame->transaction->success)){
                        $success = ','.$configGame->transaction->success.',';
                    }else{
                        $success = ',1,';
                    }
                    $checkStatus = strrpos('checkStatus_'.$data['statusAll'],$success);
                    if(isset($checkStatus) && $checkStatus > 1){
                        $status = "Thành công";
                    }else{
                        $status = "Thất bại";
                    }
                }
            }else{
                if($data['status'] == 1){
                    $status = "Thành công";
                }else{
                    $status = "Thất bại";
                }
            }
            if($status == "Thành công"){
                $statusStyle = $textStyle;
            }else{
                $statusStyle = $textStyleFalse;
            }
            $worksheet1->writeNumber($num_row, $num_column, $stt, $sttStyle);
            $worksheet1->writeString($num_row, ++$num_column, $data['transaction_id'], $textStyle);
            if(isset($configGame->transaction->tranPartner) && $configGame->transaction->tranPartner == 1){
                if(isset($data['agent_transaction_id'])) {
                    $worksheet1->writeString($num_row, ++$num_column, $data['agent_transaction_id'], $textStyle);
                }else{
                    $worksheet1->writeString($num_row, ++$num_column, 0, $textStyle);
                }
            }
            
            $worksheet1->writeString($num_row, ++$num_column, $data['username'], $textStyle);
            $worksheet1->writeNumber($num_row, ++$num_column, $data['knb'], $numberFormat);
            if(isset($configGame->transaction->gold) && $configGame->transaction->gold != 0){
                if(isset($data['gold'])){
                    $worksheet1->writeNumber($num_row, ++$num_column, $data['gold'], $numberFormat);
                }else{
                    $worksheet1->writeNumber($num_row, ++$num_column, 0, $numberFormat);
                }
            }
            $worksheet1->writeString($num_row, ++$num_column, date("Y-m-d H:i:s",strtotime($data['update_date'])), $textStyle);
			if(!isset($configGame->transaction->server) || (isset($configGame->transaction->server) && $configGame->transaction->server == 1)){
				$worksheet1->writeString($num_row, ++$num_column, $server, $textStyle);
			}
            if(!isset($configGame->transaction->agent_id) || (isset($configGame->transaction->agent_id) && $configGame->transaction->agent_id == 1)){
                if(isset($data['agent_id'])){
                    $worksheet1->write($num_row, ++$num_column, $data['agent_id'], $textStyle);
                }else{
                    $worksheet1->write($num_row, ++$num_column, '-', $textStyle);
                }
                
            }
            $worksheet1->writeString($num_row, ++$num_column, $status, $statusStyle);
            ++$stt;
            ++$num_row;
        }
        if(isset($totalColumn) && is_array($totalColumn)){
            $worksheet1->writeString($num_row, 0, 'Total', $textStyleTotal);
            $stt = 1;
            foreach($totalColumn as $key=>$val){
                if($stt == 1){
                    for($i = 1; $i < $key; $i++){
                        $worksheet1->writeString($num_row, $i, '', $textStyleTotal);
                    }
                    $worksheet1->setMerge($num_row,0,$num_row,$key-1);
                }
                $worksheet1->writeFormula($num_row, $key, '=SUM('.$val.'2:'.$val.$num_row.')', $numberFormatTotal);
                $stt++;
            }
        }
        
		$workbook->send($exportName.".xls"); 
		$workbook->close();
    }
}